package com.starblink.wishlist.ui

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.viewModelScope
import com.google.android.material.tabs.TabLayout
import com.starblink.android.basic.base.fragment.BaseTVMFragment
import com.starblink.android.basic.ext.bindFragment
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.string
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.guide.bean.SkGuideEnum
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.event.TrackEvent
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.user.LoginCheckInterceptor
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.basic.route.RoutePage
import com.starblink.basic.storage.SkStorage
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.wishlist.R
import com.starblink.wishlist.databinding.FragmentNavWishListBinding
import com.starblink.wishlist.widget.TabViewHolder
import com.starblink.wishlist.wishallitems.ui.WishAllItemsFragment
import com.starblink.wishlist.wishboards.ui.WishBoardsFragment

class NavWishListFragment : BaseTVMFragment<FragmentNavWishListBinding, NavWishListVM>() {

    companion object {
        fun obtainFragment(): NavWishListFragment {
            return NavWishListFragment()
        }

        const val TAB_ALL_ITEMS = 0
    }

    private val pageTitle = mutableListOf(
        CommUtils.getString(com.starblink.basic.style.R.string.all_items),
        CommUtils.getString(com.starblink.basic.style.R.string.boards)
    )

    private val allItemFrg = WishAllItemsFragment.obtainFragment()
    private val boardsFrg = WishBoardsFragment.obtainFragment()


    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentNavWishListBinding {
        return FragmentNavWishListBinding.inflate(inflater, container, false)
    }

    override fun startObserve() {
        //未登录态
        FlowBus.with<Boolean>(FlowConst.IN_WISHLIST_BOARD_BUT_NOT_LOGIN).register(this) {
            if (viewBinding.viewPager.currentItem == 1) {
                viewBinding.viewPager.currentItem = 0
            }
        }
    }


    var choiceMode_1 = false
    var choiceMode_2 = false

    override fun onResume() {
        super.onResume()
        YYLogUtils.e("resume 1111  ${this.isVisible}")
    }

    override fun initData() {
        initTabAndViewPager()

        viewBinding.ivSearch.click {
            navigationTo(RoutePage.Wishlist.WISHLIST_SEARCH)
            SpmTrackHandler.addSingleTrackData(
                SkAntEntity(
                    spmCnt = GTrackerAssistUtils.fetchElementValue(
                        if (viewBinding.tabLayout.selectedTabPosition == 0)
                            SpmPageDef.WishListEditPage_10028 else SpmPageDef.CreateWishRoute_10029,
                        SpmElementDef.Element_33003
                    ),
                )
            )
        }
        handleMutiChoice()

        /*******************控制顶部按钮显示隐藏 ↓↓↓↓↓↓↓↓ **********************************/
        //控制顶部按钮显示隐藏
        viewBinding.ivSetting.gone()
        viewBinding.ivSearch.gone()
        allItemFrg.setDataChangeListener { size, selectAll, noData ->
            index0Size = size
            noData0 = noData
            childDataChange(0)
        }
        boardsFrg.setDataChangeListener { size, selectAll, noData ->
            index1Size = size
            noData1 = noData
            childDataChange(1)
        }
    }

    private var index0Size = 0
    private var index1Size = 0
    private var noData0 = false
    private var noData1 = false
    private fun childDataChange(index: Int) {

        if (index == viewBinding.tabLayout.selectedTabPosition) {

            when (index) {
                0 -> {
                    if (index0Size > 0) {
                        viewBinding.ivSetting.visible()
                        viewBinding.ivSearch.visible()
                    } else {
                        viewBinding.ivSetting.gone()
                        viewBinding.ivSearch.gone()
                        if (noData0) {
                            noDataHandler()
                            allItemFrg.hideBtmLay()
                        }
                    }
                }

                1 -> {
                    if (index1Size > 0) {
                        viewBinding.ivSetting.visible()
                        viewBinding.ivSearch.visible()
                    } else {
                        viewBinding.ivSetting.gone()
                        viewBinding.ivSearch.gone()
                        if (noData1) {
                            noDataHandler()
                            boardsFrg.hideBtmLay()
                        }
                    }
                }
            }
        }

    }

    private fun noDataHandler() {
        viewBinding.mutiChoiceMode.gone()
//        //显示底部导航
//        FlowBus.with<Boolean>(FlowConst.HIDE_MAIN_BOTTOM_TAB)
//            .post(viewModel.viewModelScope, true)

        viewBinding.llTopTitleTxt.text = string(com.starblink.basic.style.R.string.my_wishlists)
    }

    /*******************控制顶部按钮显示隐藏 ↑↑↑↑↑↑↑↑↑↑↑↑↑↑ **********************************/


    private fun initTabAndViewPager() {
        viewBinding.viewPager.bindFragment(
            childFragmentManager,
            pageTitles = pageTitle,
            count = pageTitle.size
        )
        {
            when (it) {
                TAB_ALL_ITEMS -> allItemFrg
                else -> boardsFrg
            }
        }
        //tabLayout关联viewpager
        viewBinding.tabLayout.setupWithViewPager(viewBinding.viewPager)


        //处理tabLayout
        for (i in 0 until viewBinding.tabLayout.tabCount) {
            val tab = viewBinding.tabLayout.getTabAt(i)
            //给tab设置自定义布局
            tab!!.setCustomView(R.layout.tab_item)
            var tabVH = TabViewHolder(tab.customView!!)
            //填充数据
            tabVH.tvName.text = pageTitle[i]
            //默认选择第一项
            if (i == 0) {
                tabVH.setTabSelectedStyle()
            }
        }

        viewBinding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                TabViewHolder(tab.customView!!).setTabSelectedStyle()

                //隐藏多选
                if (choiceMode_1 && viewBinding.tabLayout.selectedTabPosition == 1) {
                    resetAllMuti(click = false)
                }
                if (choiceMode_2 && viewBinding.tabLayout.selectedTabPosition == 0) {
                    resetAllMuti(click = false)
                }

                when (viewBinding.tabLayout.selectedTabPosition) {
                    0 -> {
                        allItemFrg.canRefresh()
                        allItemFrg.syncPageSelectIndex(0)
                        SpmTrackHandler.addSingleTrackData(
                            SkAntEntity(
                                spmCnt = GTrackerAssistUtils.fetchElementValue(
                                    SpmPageDef.WishListEditPage_10028,
                                    SpmElementDef.Element_30060
                                ),
                            )
                        )
                    }

                    1 -> {
                        boardsFrg.canRefresh()
                        boardsFrg.syncPageSelectIndex(1)

                        SpmTrackHandler.addSingleTrackData(
                            SkAntEntity(
                                spmCnt = GTrackerAssistUtils.fetchElementValue(
                                    SpmPageDef.CreateWishRoute_10029,
                                    SpmElementDef.Element_30060
                                ),
                            )
                        )
                    }
                }

                childDataChange(viewBinding.tabLayout.selectedTabPosition)

            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
                TabViewHolder(tab.customView!!).setTabUnselectedStyle()
            }

            override fun onTabReselected(tab: TabLayout.Tab) {}
        })

        //默认选中第一个
        viewBinding.tabLayout.getTabAt(0)?.select()
        checkCanClickBoards()
        FlowBus.with<Boolean>(FlowConst.LOGIN_STATUS_CHANGE).register(this) {
            checkCanClickBoards()
        }
        FlowBus.with<Boolean>(FlowConst.SWITCH_TO_HOME_PAGE_WISHLIST).register(this) {
            resetAllMuti(click = false)
        }
    }

    private fun checkCanClickBoards() {
        if (UserDataCenter.isLogin()) {
            viewBinding.tabLayout.resetDisableClickPosition()
        } else {
            viewBinding.tabLayout.disableClickPosition = 1
            viewBinding.tabLayout.disableClickPositionListener = {
                LoginCheckInterceptor.check2Login(mActivity) {
                    checkCanClickBoards()
                    viewBinding.tabLayout.getTabAt(1)?.select()
                }
            }
        }
    }

    /**
     * 处理多选
     */
    private fun handleMutiChoice() {


        viewBinding.ivSetting.click {
            // 第一页
            if (viewBinding.tabLayout.selectedTabPosition == 0) {
                choiceMode_1 = !choiceMode_1
                allItemFrg.intoMutiSelect(choiceMode_1)
                if (choiceMode_1) {
                    clickRightTopSetting()
                }
                SpmTrackHandler.addSingleTrackData(
                    SkAntEntity(
                        spmCnt = GTrackerAssistUtils.fetchElementValue(
                            SpmPageDef.WishListEditPage_10028,
                            SpmElementDef.Element_33062
                        ),
                    )
                )
            } else {
                choiceMode_2 = !choiceMode_2
                boardsFrg.intoMutiSelect(choiceMode_2)
                if (choiceMode_2) {
                    clickRightTopSetting()
                }
                SpmTrackHandler.addSingleTrackData(
                    SkAntEntity(
                        spmCnt = GTrackerAssistUtils.fetchElementValue(
                            SpmPageDef.CreateWishRoute_10029,
                            SpmElementDef.Element_33062
                        ),
                    )
                )
            }
        }

        viewBinding.mutiChoiceMode.click {
            resetAllMuti(click = true)
        }
    }

    //点击右上设置按钮
    private fun clickRightTopSetting() {
        //搜索框隐藏
        viewBinding.ivSearch.gone()
        //设置隐藏
        viewBinding.ivSetting.gone()
        //gone 出现
        viewBinding.mutiChoiceMode.visible()
//        //通知底部导航隐藏
//        FlowBus.with<Boolean>(FlowConst.HIDE_MAIN_BOTTOM_TAB)
//            .post(viewModel.viewModelScope, false)

        viewBinding.llTopTitleTxt.text = "Select Items"
    }


    fun refreshAllItems() {
        if (viewBinding.tabLayout.selectedTabPosition == 0) {
            allItemFrg.canRefresh()
        }
    }

    //重置全选模式
    fun resetAllMuti(click: Boolean) {
        viewBinding.mutiChoiceMode.gone()

        if (click) {
            if (viewBinding.tabLayout.selectedTabPosition == 0) {
                choiceMode_1 = !choiceMode_1
                allItemFrg.intoMutiSelect(choiceMode_1)
            } else {
                choiceMode_2 = !choiceMode_2
                boardsFrg.intoMutiSelect(choiceMode_2)
            }
        } else {
            if (viewBinding.tabLayout.selectedTabPosition == 1) {
                choiceMode_1 = false
                allItemFrg.intoMutiSelect(false)
            } else {
                choiceMode_2 = false
                boardsFrg.intoMutiSelect(false)
            }
        }
        childDataChange(viewBinding.tabLayout.selectedTabPosition)
//        //显示底部导航
//        FlowBus.with<Boolean>(FlowConst.HIDE_MAIN_BOTTOM_TAB)
//            .post(viewModel.viewModelScope, true)

        viewBinding.llTopTitleTxt.text = string(com.starblink.basic.style.R.string.my_wishlists)
    }

}